/**
 * 在线学习
 */
<template>
    <div class="drawer">
        <el-drawer
            v-model="open"
            size="100%"
            direction="ttb"
            :destroy-on-close="true"
            :before-close="handleClose"
        >
            <template #header>
                <vp-label zh="学习" en="Learning" />
            </template>
            <el-container class="w100 h100" v-loading="loading">
                <el-aside width="250px">
                    <el-table class="w100" border :data="attachments" 
                        highlight-current-row stripe 
                        ref="tableRef"
                        :show-header="false" 
                        style="height:100%"
                        @current-change="handleCurrentChange"
                    >
                        <el-table-column
                            prop="yswjm"
                        >
                        <template #default="scope">
                            <div style="cursor: pointer;min-height: 60px;display: flex;flex-direction: column;justify-content: space-between;">
                                <div v-html="scope.row.yswjm+'.'+scope.row.hzm" style="color:#606266;" />
                                <div class="color-info" style="font-size: 11px;">
                                    <span v-if="trainingRecordId">已学/要求： {{ learnedMinutes(scope.row.id) }}分钟 / {{scope.row.yqsc}}分钟</span>
                                    <span v-else>要求时长： {{scope.row.yqsc}}分钟</span>
                                </div>
                            </div>
                        </template>
                        </el-table-column>
                    </el-table>
                </el-aside>
                <el-main class="p0">
                    <div style="width:100%;height:100%;text-align:center">
                        <VpPdfEmbed v-if="type==='PDF'" ref="vpPdfEmbedRef" :pdfUrl="`${baseUrl}/file/stream/${fileId}`" :pageNum="pageNum" @onPageChange="handlePdfPageChange" />
                        <el-image v-if="type==='IMAGE'" :preview-src-list="[imageSrc]" style="width:100%; height:100%;" fit="scale-down" :src="imageSrc">
                        </el-image>
                        <video v-if="type==='VIDEO'" style="width:100%;height:100%;object-fit:scale-down;" id="videoId" controls :autoplay="true" name="media" >
                            <source :src="`${baseUrl}/file/stream/${fileId}`" />
                        </video>
                        <audio v-if="type==='AUDIO'" :autoplay="true" style="position:absolute; top:50%; left:0;right:0;margin-left:auto; margin-right:auto" :src="`${baseUrl}/file/stream/${fileId}`" controls></audio>
                        <el-empty v-if="type==='OTHER'" description="暂时无法在线学习该课件，点击下方按钮可下载课件。" class="h100">
                            <el-button
                                @click="downloadAttachment(currentRow)"
                                type="primary"
                            >
                                <el-icon><ele-Download /></el-icon> <vp-label zh="下载" en="Download" />
                            </el-button>
                        </el-empty>
                    </div>
                </el-main>
            </el-container>
            <div class="page-bottom" v-if="learningProgress.zxxxbs && (learningProgress.zxxxbs === 30 || learningProgress.zxxxbs === 99)">
                <el-space>
                    <el-button type="primary" @click="finishStudy"><vp-label zh="结束学习" en="Finish Learning" /></el-button>
                </el-space>
            </div>
        </el-drawer>
    </div>
</template>
<script setup lang="ts" name="vpOnlineLearning">
import { onUnmounted, ref, watch, nextTick } from 'vue'
import request from '/@/utils/request';
import VpMessageBox from '/@/components/vp/VpMessageBox';
import VpPdfEmbed from '/@/components/vp/pdf/VpPdfEmbed.vue';
import commonFunction from '/@/utils/commonFunction';

const emits = defineEmits(['close']);
const open = ref(false);
const courseId = ref('');
const trainingRecordId = ref('');
const loading = ref(false);
const attachments = ref([]);
const currentRow = ref({} as any);
const type = ref('');
const fileSrcId = ref('');
const fileId = ref('');
const imageSrc = ref('');
const baseUrl = ref(import.meta.env.VITE_API_URL);
const ws = ref();
const interval = ref();
const pageNum = ref(1);
const learningProgress = ref({
    relocation: 0,
    zxxxbs: 10,
    records: []
});

const tableRef = ref();

watch(()=>currentRow.value, (newVal, oldVal)=>{
    closeWebSocket();
    if(newVal && newVal.id){
        fileSrcId.value=newVal.id;
        fileId.value=newVal.id;
        if (newVal.hzm == 'PNG' || newVal.hzm == 'JPG' || newVal.hzm == 'BMP') {
            type.value="IMAGE"
            request.get(`/file/base64/${fileId.value}`).then(res => {
                imageSrc.value = "data:application/png;base64,"+res.data
            });
        } else if (newVal.hzm == 'DOC' || newVal.hzm == 'DOCX' || newVal.hzm == 'PPT' || newVal.hzm == 'PPTX' || 
                newVal.hzm == 'XLS' || newVal.hzm == 'XLSX' || newVal.hzm == 'TEXT' || newVal.hzm == 'TXT') {
            loading.value = true;
            request.post(`/file/convert/${fileId.value}`).then(res => {
                loading.value = false;
                fileId.value=newVal.id+"_pdf";
                type.value="PDF"
            });
        } else if (newVal.hzm == 'PDF') {
            type.value="PDF"
        } else if(newVal.hzm == "MP4"){
            type.value="VIDEO"
        } else if(newVal.hzm == "MP3"){
            type.value="AUDIO"
        } else{
            type.value="OTHER"
        }
        if(type.value !== "OTHER"){
            initWebSocket();
        }
    }else{
        type.value = "";
        fileId.value = "";
    }
})

const handleOpen=(param: any)=>{
    courseId.value = param.courseId;
    trainingRecordId.value = param.trainingRecordId;
    attachments.value= [];
    currentRow.value={};
    learningProgress.value={
        relocation: 0,
        zxxxbs: 10,
        records: []
    };
    type.value= "";
    fileId.value= "";
    imageSrc.value= "";
    open.value = true;
    loadCourse();
}

const loadCourse = () => {
    if (courseId.value) {
        loading.value = true;
        request.get(`/training/course/${courseId.value}`).then(res => {
            attachments.value = res?.data?.textBooks || [];
            if(attachments.value && attachments.value.length >0){
                tableRef.value.setCurrentRow(attachments.value[0]);
            }
        }).finally(()=>{
            loading .value= false;
        })
    }
}

const handleCurrentChange = (val: any) =>{
    currentRow.value = val;
}

onUnmounted(()=>{
    closeWebSocket();
})

const initWebSocket =() =>{
    closeWebSocket();
    if (!trainingRecordId.value) {
        return;
    }
    const wsuri = `${location.protocol ==='https'?'wss':'ws'}:${location.host}${baseUrl.value}/ws/online/learning/${trainingRecordId.value}/${fileSrcId.value}`;
    const webSocket = new WebSocket(wsuri);
    webSocket.onmessage = (event)=>{
        learningProgress.value = {
            ...JSON.parse(event.data)
        };
        // 视频和pdf重新定位
        if (learningProgress.value.relocation === 1) {
            handleRelocation();
        }
    }
    webSocket.onclose = ()=>{
    }
    webSocket.onerror = ()=>{
        VpMessageBox.confirm(
            { zh: '网络连接中断，点击确定重新连接', en: 'Network Connection Lost. Click Confirm to Reconnect.'}, 
            { zh: '提示', en: 'Info'}, {
            type: 'warning',
        }).then(()=>{
            initWebSocket();
        });
        //closeWebSocket();
    }
    // 监听socket打开
    webSocket.onopen = function() {
    };
    ws.value = webSocket;
    interval.value = setInterval(()=>{
        let message = 'ping';
        if (type.value === 'PDF') {
            message = parseInt(pageNum.value + '') + '';
        }
        if (type.value === 'VIDEO') {
            const video = document.getElementById("videoId") as any;
            if (video && video.currentTime) {
                message = parseInt(video.currentTime) + '';
            }
        }
        webSocket.send(message);
    }, 1000*60)
}

const closeWebSocket = ()=>{
    if(interval.value){
        clearInterval(interval.value);
        interval.value = null;
    }
    if(ws.value){
        ws.value.close();
        ws.value = null;
    }

}

// 关闭前的回调
const handleClose = (done: () => void)=>{
    closeWebSocket();
    done();
    emits("close");
}

const {downloadFile} = commonFunction();

// 下载文件
const downloadAttachment = (attachment: any) => {
    downloadFile({
        id: attachment.id,
        wbwjm: attachment.wbwjm,
        hzm: attachment.hzm,
    });
};

// pdf翻页
const handlePdfPageChange = (data: any) => {
    pageNum.value = data.pageNum;
}

const finishStudy = () => {
    closeWebSocket();
    open.value = false;
    emits("close");
}

// 已学时长
const learnedMinutes = (kjid: string) => {
    const record = (learningProgress.value.records || []).find((record: any) => {
        return record.kjid === kjid;
    }) as any;
    if (record && record.xxscMin) {
        return record.xxscMin;
    }
    return 0;
}

const vpPdfEmbedRef = ref();

// 视频和pdf重新定位
const handleRelocation = () => {
    nextTick(() => {
        const kjid = currentRow.value.id;
        const record = (learningProgress.value.records || []).find((record: any) => {
            return record.kjid === kjid;
        }) as any;
        if (record && record.xxjd) {
            if (type.value === 'PDF') {
                pageNum.value = record.xxjd;
                vpPdfEmbedRef.value.setPage(record.xxjd);
            }
            if (type.value === 'VIDEO') {
                const video = document.getElementById("videoId") as any;
                if (video) {
                    video.currentTime = record.xxjd;
                }
            }
        }
    })
}

defineExpose({
    handleOpen,
})

</script>
<style lang="scss" scoped>
.drawer{
    :deep(.el-drawer__header) {
        margin-bottom: 0px !important;
    }
}
.page-bottom{
    position: absolute;
    bottom: 0;
    width: 100%;
    border-radius: var(--el-border-radius-base);
    border: 1px solid var(--el-border-color);
    padding-top: 10px;
    padding-bottom: 10px;
    background-color:var(--el-bg-color);
    text-align: center;
    box-shadow: var(--el-box-shadow);
}
</style>